<?php

namespace app\controller\Api\V1\Client;

use app\model\ClientEnroll;
use app\model\Server;
use app\request\Enroll;
use Exception;
use Illuminate\Support\Str;
use support\Log;
use support\Request;
use support\Response;

class EnrollController
{

    /**
     * 客户端登记授权
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function Enroll(Request $request): Response
    {

        $validate = new Enroll;

        if (!$validate->scene('enroll')->check($request->all())) {
            throw new Exception($validate->getError(), 500);
        }

        // 开服IP验证
        $serverSql = Server::query()->where('instance_ip', $request->getRealIp())
            ->where('open_at', '<', date('Y-m-d H:i:s'))
            ->where('expire_at', '>', date('Y-m-d H:i:s'))
            ->where('state', 1);

        $serverVerify = (clone $serverSql)->exists();

        if (!$serverVerify) {
            throw new Exception('非法验证', 500);
        }
        $serverInfo = (clone $serverSql)->first()->toArray();

        // code 验证
        if (Str::upper(md5($request->getRealIp())) !== $request->input('code')) {
            throw new Exception('非法验证', 500);
        }

        try {
            ClientEnroll::query()->updateOrCreate([
                'ip' => $request->getRealIp(),
                'code' => $request->input('code'),
            ], [
                'merchant' => $serverInfo['merchant'],
                'server' => $serverInfo['ulid'],
                'game' => $serverInfo['game'],
                'type' => $request->input('release_type') ?? 1,
                'state' => 1,
            ]);
        } catch (Exception $e) {
            Log::info('登记失败：' . $e);
            throw new Exception('登记失败', 500);
        }

        return jsonRe([
            'game_id' => $serverInfo['game'],
        ]);

    }

}